'use strict';

const {
	verifyToken
} = require("wx-common");

exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)

	const db = uniCloud.database();
	const dbCmd = db.command;

	const action = event.action;

	const payload = verifyToken(event.token);

	const now = new Date().getTime();

	let dbRes;

	if (action === "add") {
		//doc(数据库表某记录id)比where性能高
		const bookInfo = await db.collection("isbnlib").doc(event.isbnid).get();

		dbRes = await db.collection("books").add({
			owner: payload.openid, //openid
			shelfid: event.shelfid,
			title: bookInfo.data[0].title,
			cover_url: bookInfo.data[0].cover_url,
			isbn: bookInfo.data[0].isbn,
			isbnid: event.isbnid,
			createtime: now,
			updatetime: now
		})

		await db.collection("bookshelfs").where({
			owner: payload.openid,
			_id: event.shelfid
		}).update({
			totalbook: dbCmd.inc(1) //increase
		})
		return dbRes;
	} else if (action === "listbyshelf") {
		dbRes = await db.collection("books")
			.field({
				owner: false
			}) //可以过滤owner这个字段，不让显示
			.where({
				shelfid: dbCmd.eq(event.shelfid)
			})
			.limit(9)
			.get();

		// const $ = db.command.aggregate;//聚合查询

		// dbRes = await db.collection("books").aggregate().group({
		// 	"_id": "$isbnid",
		// 	"isbnid": $.last("$isbnid"),
		// 	"title": $.last("$title"),//取最后一项的字段值为聚合后的字段值
		// 	"cover_url": $.last("$cover_url")
		// }).sort({
		// 	"_id": -1 ,//desc 排序
		// }).end();

		return dbRes.data;
	} else if (action == "movetop") {
		dbRes = await db.collection("books").where({
			_id: dbCmd.eq(event.bookid),
			owner: dbCmd.eq(payload.openid)
		}).update({
			updatetime: now
		});
		return dbRes;
	} else if (action == "listall") {
		let option = {}
		if (event.start) option._id = dbCmd.lt(event.start);
		if (event.keyword) option.title = new RegExp(event.keyword, 'i');

		dbRes = await db.collection('isbnlib').where(option)
			.orderBy("_id", "desc")
			.orderBy("updatetime", "desc")
			.limit(12)
			.get();
			
	} else if (action == "get") {
		dbRes = await db.collection("isbnlib").where({
			isbn: dbCmd.eq(event.isbn)
		}).get();

		console.log(dbRes);

		let bookInfo = dbRes.data[0];

		bookInfo.abstract = bookInfo.abstract.replace(/\//g, "\r\n");

		return bookInfo;
	}
	//返回数据给客户端
	return dbRes.data;
};
